import sys
from PyQt5 import QtCore
from PyQt5.QtWidgets import QApplication, QDialog, QMainWindow
from ui_login import Ui_Login
from PyQt5.QtGui import QIntValidator
import requests
from network import Network


class LoginWindow(QDialog, Ui_Login):

    show_main_signal = QtCore.pyqtSignal()
    show_reg_signal = QtCore.pyqtSignal()

    def __init__(self, parent=None):
        super(LoginWindow, self).__init__(parent=parent)
        self.setupUi(self)
        self.loginBtn.clicked.connect(self.login)
        self.passwordEdit.textChanged.connect(
            lambda: self.isEnpty(self.passwordEdit))
        self.usernameEdit.textChanged.connect(
            lambda: self.isEnpty(self.passwordEdit))
        self.usernameEdit.setValidator(QIntValidator())

        self.regBtn.clicked.connect(self.Reg)

        self.username: str

    def isEnpty(self, lineEdit):
        if lineEdit.text() == "":
            self.loginBtn.setEnabled(False)
            return
        if self.passwordEdit.text() != "" and self.usernameEdit.text() != "":
            self.loginBtn.setEnabled(True)

    def login(self):
        if Network.login(self.usernameEdit.text(), self.passwordEdit.text()) == True:
            self.username = self.usernameEdit.text()
            self.show_main_signal.emit()
            self.close()

    def Reg(self):
        self.show_reg_signal.emit()


if __name__ == "__main__":
    app = QApplication(sys.argv)
    myWin = LoginWindow()
    myWin.show()
    sys.exit(app.exec())
